
#include "napi/native_api.h"
#include "IPC/IpcCapiProxyTest.h"
#include <cstdint>
#include <thread>
#include <chrono>

using namespace std::chrono_literals;

static IpcCApiProxyTest *g_ipcProxy = nullptr;

// 元能力打通IPC通道回调接口
void OnNativeChildProcessStarted(int errCode, OHIPCRemoteProxy *remoteProxy) {
    OH_LOG_INFO(LOG_APP, "OnNativeChildProcessStarted proxy=%{public}p err=%{public}d", remoteProxy, errCode);
    if (remoteProxy == nullptr) {
        return;
    }
    g_ipcProxy = new (std::nothrow) IpcCApiProxyTest(remoteProxy);
    if (g_ipcProxy == nullptr) {
        OH_IPCRemoteProxy_Destroy(remoteProxy);
        OH_LOG_ERROR(LOG_APP, "Alloc IpcCApiProxyTest object failed");
        return;
    }
}

static napi_value Add(napi_env env, napi_callback_info info)
{
    size_t argc = 2;
    napi_value args[2] = {nullptr};

    napi_get_cb_info(env, info, &argc, args , nullptr, nullptr);

    napi_valuetype valuetype0;
    napi_typeof(env, args[0], &valuetype0);

    napi_valuetype valuetype1;
    napi_typeof(env, args[1], &valuetype1);

    int value0;
    napi_get_value_int32(env, args[0], &value0);

    int value1;
    napi_get_value_int32(env, args[1], &value1);

//     napi_value sum;
//     napi_create_double(env, value0 + value1, &sum);
    
//     int32_t ret = OH_Ability_CreateNativeChildProcess("libIPC.so", OnNativeChildProcessStarted);
//     if (ret != 0) {
//         OH_LOG_ERROR(LOG_APP, "OH_Ability_CreateNativeChildProcess failed");
//         return sum;
//     }
//     std::this_thread::sleep_for(1ms);
    if (g_ipcProxy == nullptr) {
        OH_LOG_ERROR(LOG_APP, "g_ipcProxy == nullptr failed");
        napi_value ret;
        napi_create_int32(env, -1, &ret);
        return ret;
    }
    int32_t result = 0;    
    int32_t ret = g_ipcProxy->AsyncAdd(value0, value1, result);
    OH_LOG_INFO(LOG_APP, "AsyncAdd: %{public}d + %{public}d = %{public}d, ret=%{public}d", value0, value1, result, ret);
    
    napi_value sum;
    napi_create_int32(env, result, &sum);
    return sum;

}

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
    napi_property_descriptor desc[] = {
        { "add", nullptr, Add, nullptr, nullptr, nullptr, napi_default, nullptr }
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    int32_t ret = OH_Ability_CreateNativeChildProcess("libIPC.so", OnNativeChildProcessStarted);
    if (ret != 0) {
        OH_LOG_ERROR(LOG_APP, "OH_Ability_CreateNativeChildProcess failed");
    }
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "entry",
    .nm_priv = ((void*)0),
    .reserved = { 0 },
};

extern "C" __attribute__((constructor)) void RegisterEntryModule(void)
{
    napi_module_register(&demoModule);
}
